package com.source.hotelbath.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.source.hotelbath.MainActivity;
import com.source.hotelbath.R;
import com.source.hotelbath.base.BizActivity;
import com.source.hotelbath.model.GetGoodsBean;
import com.source.hotelbath.model.GetOrderBean;
import com.source.hotelbath.model.GoodsListBean;
import com.source.hotelbath.model.OperateBean;
import com.source.hotelbath.model.OrderBean;
import com.source.hotelbath.model.OrderGoodsList;
import com.source.hotelbath.model.PostBean;
import com.source.hotelbath.model.SubGetBean;
import com.source.hotelbath.net.CustomerRequestConstants;
import com.source.hotelbath.net.RequestConstants;
import com.source.hotelbath.net.response.GoodsListResponse;
import com.source.hotelbath.net.response.OrderDetailResponse;
import com.source.hotelbath.net.response.OrderSubmitResponse;
import com.source.hotelbath.utils.DialogCallback;
import com.source.hotelbath.utils.SharedPreferencesUtils;
import com.source.hotelbath.utils.TintDrawable;
import com.source.hotelbath.utils.ToolsUtil;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.weipass.pos.sdk.IPrint;
import cn.weipass.pos.sdk.LatticePrinter;
import cn.weipass.pos.sdk.impl.WeiposImpl;

public class OrderDeatilActivity extends BizActivity {

    private ListView lv_for;
    private TextView tv_hotel;
    private TextView tv_person;
    private TextView tv_phone;
    private TextView tv_remek;

    private Button btn_submit;
    private LinearLayout ll_header_left;
    private LinearLayout ll_header_right;

    private List<PostBean> orderGoodsList=new ArrayList<>();
    private OrderItemAdapter orderAdapter;
    public static String path= Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qm.png";
    private String order;
    private int orderId;
    private List<GetGoodsBean> beanList=new ArrayList<>();
    private List<GetOrderBean> goodsList=new ArrayList<>();
    private List<OperateBean> operateList =new ArrayList<>();
    private String status;
    private int goodsNum;
    private String orderMoney;
    private Button btn_sign;
    private ListView lv_operate;
    private OperateAdapter adapter;
    private LatticePrinter latticePrinter;// 点阵打印
    private int sums;
    private String total;
    private OrderBean orderBean;
    private TextView tv_order_num;
    private TextView create_time;
    private ImageView iv_sign;
    private LinearLayout ll_sign;

    @Override
    protected void onBaseCreate(Bundle var1) {
        setContentView(R.layout.activity_order_deatil);
    }

    Handler myHandler = new Handler() {



        public void handleMessage(Message msg) {
            int type=msg.what;
            switch (type){
                case 1:   //布草数量有变化
                    total = (String) msg.obj;
                    sums = msg.arg1;
                    break;

            }

            super.handleMessage(msg);
        }
    };

    @Override
    protected void bindView(Bundle var1) {

        orderId = getIntent().getIntExtra("orderId",0);
        status=getIntent().getStringExtra("status");

        ll_header_left = (LinearLayout) findViewById(R.id.ll_header_left);
        ll_header_right = (LinearLayout) findViewById(R.id.ll_header_right);
        ll_header_right.setVisibility(View.GONE);
        ll_header_left.setOnClickListener(this);
        TextView tv_header_title= (TextView) findViewById(R.id.tv_header_title);
        tv_header_title.setText("订单详情");
        lv_for = (ListView) findViewById(R.id.lv_for);
        lv_operate = (ListView) findViewById(R.id.lv_operate);
        tv_hotel = (TextView) findViewById(R.id.tv_hotel);
        tv_person = (TextView) findViewById(R.id.tv_person);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_remek = (TextView) findViewById(R.id.tv_remek);
        tv_order_num = (TextView) findViewById(R.id.tv_order_num);
        create_time = (TextView) findViewById(R.id.create_time);
        iv_sign = (ImageView) findViewById(R.id.iv_sign);
        ll_sign = (LinearLayout) findViewById(R.id.ll_sign);
        ll_sign.setVisibility(View.GONE);
        btn_sign = (Button) findViewById(R.id.btn_sign);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        if ("04".equals(status)){
            btn_submit.setVisibility(View.GONE);
        }else {
            try {
                // 设备可能没有打印机，open会抛异常
                latticePrinter = WeiposImpl.as().openLatticePrinter();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        btn_submit.setOnClickListener(this);
        btn_sign.setOnClickListener(this);
        orderAdapter = new OrderItemAdapter(this,goodsList,myHandler,status);
        adapter = new OperateAdapter(this,operateList);
        lv_for.setAdapter(orderAdapter);
        lv_operate.setAdapter(adapter);
    }

    @Override
    protected void afterCreate() {
        super.afterCreate();
        OkGo.<OrderDetailResponse>get(CustomerRequestConstants.newUrl + CustomerRequestConstants.ORDER_DETAIL_COMMOND+"?orderId="+orderId)//
                .tag(this)//
                .execute(new DialogCallback<OrderDetailResponse>(OrderDeatilActivity.this, true) {
                    @Override
                    public void onSuccess(Response<OrderDetailResponse> response) {
                        OrderDetailResponse detailResponse=response.body();
                        if (detailResponse!=null){

                            if (detailResponse.getOrder()!=null){
                                orderBean=detailResponse.getOrder();
                                tv_hotel.setText("酒店名称："+orderBean.getHotelName());
                                tv_remek.setText("备注信息："+orderBean.getRemark());
                                tv_order_num.setText("订单编号："+orderBean.getOrderCode());
                                create_time.setText("创建时间："+orderBean.getCreateTimeDescp());
                                tv_person.setText("操作人员："+ orderBean.getOperatorName());
                                tv_phone.setText("联系电话："+ orderBean.getOperatorPhone());

                                goodsNum=detailResponse.getOrder().getGoodsNum();
                                orderMoney=detailResponse.getOrder().getOrderMoney();
                                orderAdapter.add(goodsNum,orderMoney);

                            }
                            if (detailResponse.getGoodsList()!=null){
                                goodsList.clear();
                                goodsList.addAll(detailResponse.getGoodsList());
                                orderAdapter.notifyDataSetChanged();
                            }
                            if (detailResponse.getOperateList()!=null){
                                operateList.clear();
                                operateList.addAll(detailResponse.getOperateList());
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<OrderDetailResponse> response) {
                        super.onError(response);

                        Toast.makeText(OrderDeatilActivity.this, "请求网络失败", Toast.LENGTH_SHORT).show();
                    }

                });
    }
    private int click;
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view==ll_header_left){
            finish();
        }else if (view==btn_submit){
            startActivityForResult(new Intent(OrderDeatilActivity.this, SignActivity.class), 1);
        }else if (view==btn_sign){
            click+=1;
            btn_sign.setText("打印小票第2次");
            //点阵打印
            if (latticePrinter == null) {
                Toast.makeText(OrderDeatilActivity.this, "尚未初始化点阵打印sdk，请稍后再试", Toast.LENGTH_SHORT).show();
                return;
            }
            // 打印内容赋值
            latticePrinter.setOnEventListener(new IPrint.OnEventListener() {

                @Override
                public void onEvent(final int what, String in) {
                    // TODO Auto-generated method stub
                    final String info = in;
                    // 回调函数中不能做UI操作，所以可以使用runOnUiThread函数来包装一下代码块
                    runOnUiThread(new Runnable() {
                        public void run() {
                            final String message = ToolsUtil.getPrintErrorInfo(what, info);
                            if (message == null || message.length() < 1) {
                                return;
                            }
                            showResultInfo("打印", "打印结果信息", message);
                        }
                    });
                }
            });
            if (TextUtils.isEmpty(total)){
                total=orderBean.getOrderMoney();
            }
            ToolsUtil.printLattice(OrderDeatilActivity.this, latticePrinter,goodsList,operateList,orderBean,total,sums);
            if (click==2){
                btn_sign.setClickable(false);
                btn_sign.setText("打印结束");
                btn_sign.setBackgroundResource(R.drawable.grey_btn);
            }
        }
    }

    private void showResultInfo(String operInfo, String titleHeader, String info) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setMessage(titleHeader + ":" + info);
        builder.setTitle(operInfo);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==100)
        {//请求网络提交订单

                             for (int i=0;i<goodsList.size();i++){
                                 GetGoodsBean bean = new GetGoodsBean();
                                      bean.setId(goodsList.get(i).getId());
                                      if (goodsList.get(i).isChange()){
                                          bean.setNumGet(goodsList.get(i).getNumGet());
                                      }else {
                                          bean.setNumGet(goodsList.get(i).getNum());
                                      }

                                      beanList.add(bean);
                                  }
            SubGetBean  ordergoods=new SubGetBean();
                                  ordergoods.setOrderGoodsList(beanList);
                                  ordergoods.setId(orderId);
//                                  ordergoods.setRemark("备注信息");
                                  order=new Gson().toJson(ordergoods);
            Log.d("order",order);
            OkGo.<OrderSubmitResponse>post(CustomerRequestConstants.newUrl+CustomerRequestConstants.ORDER_GET_COMMOND)//
                    .tag(this)//
                    .params("sign",new File(path))   //这种方式为一个key，对应一个文件
                    .params("order",order)
                    // 这种方式为同一个key，上传多个文件
                    .execute(new DialogCallback<OrderSubmitResponse>(OrderDeatilActivity.this,true) {
                        @Override
                        public void onSuccess(Response<OrderSubmitResponse> response) {
                            OrderSubmitResponse submitResponse=response.body();
                            if (submitResponse!=null){
                                if (submitResponse.isSuccess()){
                                    Intent intents = new Intent(CustomerRequestConstants.REFRESH_ORDER);

                                    LocalBroadcastManager.getInstance(OrderDeatilActivity.this).sendBroadcast(intents);
                                    btn_sign.setVisibility(View.VISIBLE);
                                    ll_sign.setVisibility(View.VISIBLE);
                                    btn_submit.setVisibility(View.GONE);
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inSampleSize = 2;
                                    Bitmap bm = BitmapFactory.decodeFile(path, options);
                                    iv_sign.setImageBitmap(bm);
                                }else {
                                    Toast.makeText(OrderDeatilActivity.this,"提交失败",Toast.LENGTH_SHORT).show();
                                }

                            }
                        }

                        @Override
                        public void onError(Response<OrderSubmitResponse> response) {
                            super.onError(response);
                            Toast.makeText(OrderDeatilActivity.this,"提交失败",Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }
}
